﻿using DotNetCore.CAP;
using DotNetCore.CAP.Internal;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Savorboard.CAP.InMemoryMessageQueue;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using TK.Common.CAP;
using TK.Common.Tools;

namespace Microsoft.Extensions.DependencyInjection
{
    /// <summary>
    /// cap 服务注册
    /// </summary>
    public static class CapExtensions
    {
        /// <summary>
        /// cap分布式服务注入,默认内存内传输及存储
        /// </summary>
        public static IServiceCollection AddTKCap(this IServiceCollection services, Action<CapOptions> setupAction = null)
        {
            services.AddCap(options =>
            {
                if (setupAction != null)
                {
                    setupAction(options);
                }
                else
                {
                    options.UseDispatchingPerGroup = true;
                    options.UseStorageLock= true;
                    options.JsonSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
                    options.UseInMemoryStorage();
                    options.UseInMemoryMessageQueue();
                }
            }).AddSubscribeFilter<CapSubFilter>();
            services.Replace(new ServiceDescriptor(typeof(IConsumerServiceSelector),
            x => new CustomConsumerServiceSelector(x),
            ServiceLifetime.Singleton));

            return services;
        }
    }
}
